package com.ApiBack.springbootinit.controller;

import com.ApiBack.springbootinit.annotation.AuthCheck;
import com.ApiBack.springbootinit.common.BaseResponse;
import com.ApiBack.springbootinit.common.DeleteRequest;
import com.ApiBack.springbootinit.common.ErrorCode;
import com.ApiBack.springbootinit.common.ResultUtils;
import com.ApiBack.springbootinit.constant.CommonConstant;
import com.ApiBack.springbootinit.constant.UserConstant;
import com.ApiBack.springbootinit.exception.BusinessException;
import com.ApiBack.springbootinit.exception.ThrowUtils;
import com.ApiBack.springbootinit.model.dto.interfaceinfo.InterfaceAddRequest;
import com.ApiBack.springbootinit.model.dto.interfaceinfo.InterfaceQueryRequest;
import com.ApiBack.springbootinit.model.dto.interfaceinfo.InterfaceUpdateRequest;
import com.ApiBack.springbootinit.model.dto.userInterface.UserInterfaceAddRequest;
import com.ApiBack.springbootinit.model.dto.userInterface.UserInterfaceQueryRequest;
import com.ApiBack.springbootinit.model.dto.userInterface.UserInterfaceUpdateRequest;
import com.ApiBack.springbootinit.model.entity.InterfaceInfo;
import com.ApiBack.springbootinit.model.entity.User;
import com.ApiBack.springbootinit.model.entity.UserInterfaceInfo;
import com.ApiBack.springbootinit.service.UserInterfaceInfoService;
import com.ApiBack.springbootinit.service.UserService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.List;

/**
 * Description:    // 类说明
 *
 * @ClassName: UserInterfaceController    // 类名，会自动填充
 * @Author: 周天赐        // 创建者
 * @Email: m18879004515@163.com
 * @Date: 2024/3/1 13:05   // 时间
 * @Version: 1.0     // 版本
 */
@RestController
@RequestMapping("userInterfaceInfo")
@Slf4j
@CrossOrigin(origins = {"http://8.130.82.61","http://124.221.241.140"},allowCredentials = "true")
public class UserInterfaceController {

    @Resource
    private UserInterfaceInfoService userInterfaceInfoService;

    @Resource
    private UserService userService;

    /**
     * 用户-接口信息的增删改查
     */

    @PostMapping("/add")
    public BaseResponse<Long>addUserInterfaceInfo(@RequestBody UserInterfaceAddRequest userInterfaceAddRequest, HttpServletRequest request) {
        if (userInterfaceAddRequest == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        UserInterfaceInfo userInterfaceInfo = new UserInterfaceInfo();
        BeanUtils.copyProperties(userInterfaceAddRequest, userInterfaceInfo);
        // 校验
        userInterfaceInfoService.validInterfaceInfo(userInterfaceInfo, true);
        User loginUser = userService.getLoginUser(request);
        userInterfaceInfo.setUserId(loginUser.getId());
        boolean result = userInterfaceInfoService.save(userInterfaceInfo);
        if (!result) {
            throw new BusinessException(ErrorCode.OPERATION_ERROR);
        }
        long newInterfaceInfoId = userInterfaceInfo.getId();
        return ResultUtils.success(newInterfaceInfoId);
    }


    /**
     * 删除
     *
     * @param
     * @param request
     * @return
     */
    @PostMapping("/delete")
    public BaseResponse<Boolean> deleteUserInterfaceInfo(@RequestBody DeleteRequest deleteRequest, HttpServletRequest request) {
        if (deleteRequest == null || deleteRequest.getId() <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        User user = userService.getLoginUser(request);
        long id = deleteRequest.getId();
        // 判断是否存在
        UserInterfaceInfo userInterface = userInterfaceInfoService.getById(id);
        if (userInterface == null) {
            throw new BusinessException(ErrorCode.NOT_FOUND_ERROR);
        }
        // 仅本人或管理员可删除
        if (!userInterface.getUserId().equals(user.getId()) && !userService.isAdmin(request)) {
            throw new BusinessException(ErrorCode.NO_AUTH_ERROR);
        }
        boolean b = userInterfaceInfoService.removeById(id);
        return ResultUtils.success(b);

    }

    /**
     * 更新（仅管理员）
     *
     * @param
     * @return
     */
    @PostMapping("/update")
    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    public BaseResponse<Boolean> updateUserInterfaceInfo(@RequestBody UserInterfaceUpdateRequest userInterfaceUpdateRequest, HttpServletRequest request) {
        if (userInterfaceUpdateRequest == null || userInterfaceUpdateRequest.getId() <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        UserInterfaceInfo userInterfaceInfo = new UserInterfaceInfo();
        BeanUtils.copyProperties(userInterfaceUpdateRequest, userInterfaceInfo);
        User loginUser = userService.getLoginUser(request);

        // 参数校验
        userInterfaceInfoService.validInterfaceInfo(userInterfaceInfo, false);
        long id = userInterfaceUpdateRequest.getId();
        // 判断是否存在
        UserInterfaceInfo oldUserInterface = userInterfaceInfoService.getById(id);
        ThrowUtils.throwIf(oldUserInterface == null, ErrorCode.NOT_FOUND_ERROR);
        //鉴权,只有管理员和本人才能够修改
        if (!oldUserInterface.equals(loginUser.getId()) && !userService.isAdmin(request)) {
            throw new BusinessException(ErrorCode.NO_AUTH_ERROR);
        }
        boolean result = userInterfaceInfoService.updateById(userInterfaceInfo);
        return ResultUtils.success(result);
    }

    /**
     * 根据 id 获取
     *
     * @param
     * @return
     */


    @GetMapping("/get")
    public BaseResponse<UserInterfaceInfo> getUserInterfaceInfoById(long id) {
        if (id < 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }

        UserInterfaceInfo userInterface = userInterfaceInfoService.getById(id);
        return ResultUtils.success(userInterface);
    }


    /**
     * 管理员查询
     *
     * @param 
     * @return
     */
    @AuthCheck(mustRole = "admin")
    @GetMapping("/list")
    public BaseResponse<List<UserInterfaceInfo>> listInterfaceInfo(UserInterfaceQueryRequest userInterfaceQueryRequest) {
        UserInterfaceInfo userInterfaceInfo = new UserInterfaceInfo();
        if (userInterfaceQueryRequest != null) {
            BeanUtils.copyProperties(userInterfaceQueryRequest,userInterfaceInfo);
        }
        QueryWrapper<UserInterfaceInfo> queryWrapper = new QueryWrapper<>(userInterfaceInfo);
        List<UserInterfaceInfo> UserinterfaceInfoList = userInterfaceInfoService.list(queryWrapper);
        return ResultUtils.success(UserinterfaceInfoList);
    }


    /**
     * 分页获取列表（仅管理员）
     *
     * @param
     * @return
     */
    @PostMapping("/list/page")
    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    public BaseResponse<Page<UserInterfaceInfo>> listUserInterfaceInfo(@RequestBody UserInterfaceQueryRequest userInterfaceQueryRequest) {
        if (userInterfaceQueryRequest == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        UserInterfaceInfo userInterfaceInfo = new UserInterfaceInfo();
        BeanUtils.copyProperties(userInterfaceQueryRequest, userInterfaceInfo);
        long current = userInterfaceQueryRequest.getCurrent();
        long size = userInterfaceQueryRequest.getPageSize();
        String sortField = userInterfaceQueryRequest.getSortField();
        String sortOrder = userInterfaceQueryRequest.getSortOrder();
        // 限制爬虫
        if (size > 50) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        QueryWrapper<UserInterfaceInfo> queryWrapper = new QueryWrapper<>(userInterfaceInfo);
        queryWrapper.orderBy(StringUtils.isNotBlank(sortField),
                sortOrder.equals(CommonConstant.SORT_ORDER_ASC), sortField);
        Page<UserInterfaceInfo> interfaceInfoPage = userInterfaceInfoService.page(new Page<>(current, size), queryWrapper);
        return ResultUtils.success(interfaceInfoPage);

    }

}

    
    
